
import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.*;
 
@SuppressWarnings("serial")
public class InputThread extends JFrame implements KeyListener, ActionListener, Runnable
{
    JTextArea displayArea;
    int angle;
    private static final String SERVER_IP = "127.0.0.1";
	private static final int SERVER_PORT = 4567;
	   
    private String letter = "";
    private boolean win = false;
    JMenuItem newGame = new JMenuItem("New Game"),
    pause = new JMenuItem("Pause"),
    about = new JMenuItem("About"),
    exit = new JMenuItem("Exit"),
    name = new JMenuItem("Change Name");
    String player1= "Player 1";
	static Socket socket = null;
	
	// Client's Local copies of the game data structures to be used by the UI in the future
	public static QuadTree localTree = new QuadTree();
	public static ArrayList<Player> localPlayerList = new ArrayList<Player>();
	public static ArrayList<Vehicle> localVehicleList = new ArrayList<Vehicle>();

	public static void connect(){
		 try 
			{	
				socket = new Socket(SERVER_IP, SERVER_PORT);
				System.out.println("Connected to server!");
			} 
			catch (Exception e) 
			{
				System.out.println("Error connecting to server: " + e.getMessage());
			}
	}
	//System.out.println("Connected to server!");
    ObjectInputStream in = null;
		ObjectOutputStream out = null;
	
    public void run() {
    	
		connect();
		InputThread  frame = new InputThread();
		frame.setName();	
		

		ClientListeningThread listen = new ClientListeningThread(socket);
		Thread t2 = new Thread(listen);
		t2.start();
	
	}
    
     
    public void addComponentsToPane() {
         
        displayArea = new JTextArea();
        displayArea.setEditable(false);
        displayArea.setFocusable(false);
        JScrollPane scrollPane = new JScrollPane(displayArea);
        getContentPane().add(scrollPane);
        name.addActionListener(this);
        newGame.addActionListener(this);
        about.addActionListener(this);
        exit.addActionListener(this);
        pause.addActionListener(this);

    }
     
    public InputThread() {
       // super(name);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane();
        setSize(600,600);
        setVisible(true);
        JMenuBar menu = new JMenuBar();
        menu.add(newGame);
        menu.add(name);
        menu.add(pause);
        menu.add(about);
        menu.add(exit);
        setJMenuBar(menu);
        addKeyListener(this);
    }
     
    @Override
    public void keyTyped(KeyEvent e) {
        //displayInfo(e, "KEY TYPED: ");
    }
     
    public void keyPressed(KeyEvent e) {
        direct(e, "KEY PRESSED: ");
        
    }
    
    @Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
	}
     
    
    private void direct(KeyEvent e, String keyStatus){
         
            int keyCode = e.getKeyCode();
            int x=0;
           // while (true) 
          	{ 
            if(keyCode==37)
            {
            	x=1;	//Left key increases the degree
            }
            if(keyCode==39)
            {
            	x=2;	//Right key decreases the degree
            }
           
          
       		try 
       		{
       			if (out == null) 
       			{
       				out = new ObjectOutputStream(socket.getOutputStream());
       			}
       			
       			out.writeObject(new Message(x));
       			out.flush();
       		}
       		catch(Exception ez)
       		{
       			System.out.println("Error : " + ez.getMessage());
       		}
          	}
    }
    
    public void setName()
    {
    player1 = JOptionPane.showInputDialog(null, "Enter Name of player 1: ", "", 1);
    if(player1==null)
    {
    	player1 = "player 1";

    }

    if(player1.length()==0)
    {
    	player1 = "player 1";

    }
    JOptionPane.showMessageDialog(null,"Hi "+player1+"\nYour name has been set\nTo change your name click on the Change name button in the menu bar","Name Changed!!!",JOptionPane.INFORMATION_MESSAGE);
    }


    public void actionPerformed(ActionEvent a)
    {
    Object source = a.getSource();
    if(source == newGame)
    {
    int answer = JOptionPane.showConfirmDialog(null, "Your current game will not be saved...\nContinue Anyways??", "Do you want to start a new game?", JOptionPane.YES_NO_OPTION);

    if (answer == JOptionPane.YES_OPTION)
    {
    this.clearIt();
    }

    }
    else if(source == name)
    {
    this.setName();
    }
    else if(source == about)
    {
    JOptionPane.showMessageDialog(null, "Group Names \nAndrew \nNipun Gupta \nSaurabh yadav \nTanmay garg \nArushi rai","About",JOptionPane.INFORMATION_MESSAGE);

    }
    else if(source == pause)
    {
    	try {
    		JOptionPane.showMessageDialog(null, "The game will be paused for 20 secs. The element coordinates will be printed in the console","Pause",JOptionPane.INFORMATION_MESSAGE);
			ClientListeningThread.message.printleaves(ClientListeningThread.message.getRoot());
    		Game.t1.sleep(20000);
			Game.t3.sleep(20000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }
    else if(source == exit)
    {
    int answer = JOptionPane.showConfirmDialog(null, "EXIT", "Are You sure you want to exit??", JOptionPane.YES_NO_OPTION);

    if (answer == JOptionPane.YES_OPTION)
    {
    JOptionPane.showMessageDialog(null, "Thank you " + player1+ "  for playing");
    System.exit(0);
    }
    }
    else
    {
    JButton pressedButton = (JButton)source;
    pressedButton.setText(letter);
    pressedButton.setEnabled(false);



    /*Show a dialog when game is over*/
    if(win == true)
    {
    if(letter.equals("player 1"))
    letter = player1;
    JOptionPane.showMessageDialog(null, letter + " wins the game!");
    int answer = JOptionPane.showConfirmDialog(null, "Start", "Do you want to start a new game", JOptionPane.YES_NO_OPTION);

    if (answer == JOptionPane.YES_OPTION)
    {
    this.clearIt();
    }
    else
    {
    JOptionPane.showMessageDialog(null, "Thank you " + player1 + " and  for playing");
    System.exit(0);
    }
    }}}

    public void clearIt()
    {
    setVisible(false);
    dispose();
    new InputThread();    
    }   
}